import React, { useState } from "react";
import "./Register.css";
import { 
  Form, 
  Input, 
  Button, 
  message,
} from 'antd';
import {
  giveRequest,
  register,
} from "../../lib/apiconfig";


/**
 * @description 注册页面
 */
const Register = () => {
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");

   // 发送注册请求
  const sendRegister = () => {
    if ( account && password) {
      giveRequest(
        register,
        "POST",
        {
          status: "register",
          data: {
            account: account,
            password: password,
          }
        },
        res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("注册失败，请重试!");
          } else if ( status === "warning" ) {
            message.warn("该账号已存在!");
          } else {
            message.success("注册成功!");
            setTimeout(() => {
              window.location.href="/#/login";
            }, 2000);
          }
        }
      );
    } else {
      message.warn("账号和密码不能为空!");
    }
  };

  return (
    <div className="Register-page flex-column-start-center">
      <div className="Register-title">
        注册
      </div>
      <Form
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 21 }}
        className="Register-form"
        onValuesChange={data => {
          if ( data.account )
            setAccount(data.account);
          if ( data.password ) 
            setPassword(data.password);
        }}
      >
        <Form.Item label="账号" name="account" rules={[{ required: true, message: '账号不能为空!' }]}>
          <Input placeholder="请输入账号~"/>
        </Form.Item>
        <Form.Item label="密码" name="password" rules={[{ required: true, message: '密码不能为空!' }]}>
          <Input.Password placeholder="请输入密码~"/>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 3, span: 21 }}>
          <Button type="primary" style={{ width: "90px", marginRight: "30px" }} onClick={() => sendRegister()}>
            注册
          </Button>
          <Button type="primary" style={{ width: "90px" }} onClick={() => window.location.href="/#/login"}>
            前往登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Register;